import React from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useRequest } from "ahooks";
import {
  addInfoCollection,
  cancelInfoCollection,
  getInformationListDetail,
} from "../../../api/home";
import { MyHeader } from "../../../components";
import style from "./detail.module.scss";
import collect1 from "../../../assets/images/icon/common resource/hdpi/common_button_collection_small_n.png";
import collect2 from "../../../assets/images/icon/common resource/hdpi/common_button_collection_small_s.png";
import share from "../../../assets/images/icon/common resource/hdpi/common_button_share_n.png";
import { Notify, Toast } from "react-vant";
interface DataState {
  content: string;
  id: number;
  releaseTime: number;
  source: string;
  title: string;
  // 收藏 0没有收藏 1已经收藏
  whetherCollection: number;
}

const Index: React.FC = () => {
  const params = useParams();
  const infoId = params.infoId as string;
  const navigate = useNavigate();
  const location = useLocation()
  const { data = {} as DataState, run } = useRequest(async () => {
    const resp = await getInformationListDetail(infoId);
    resp.result.content = resp.result.content.replace(
      /<img /g,
      '<img width="100%" style="margin: 10px 0;"'
    );
    return resp.result as DataState;
  });

  const addCollect = async () => {
    if (data.whetherCollection === 1) {
      const resp = await cancelInfoCollection(data.id);
      Notify.show({ type: "success", message: resp.message });
    } else {
      const resp = await addInfoCollection(data.id);
      Notify.show({ type: "success", message: resp.message });
      if(resp.status === '9999') {
        navigate('/login?from=' + location.pathname, { replace: true })
        return ;
      }
    }

    await run();
  };

  return (
    <div>
      <MyHeader></MyHeader>
      {/* { data.q.q.q.q } */}
      <div className={style["con"]}>
        <h3>{data.title}</h3>
        <p style={{ margin: "10px 0", fontSize: 10, color: "#ccc" }}>
          <span>{data.source}</span>
          <span>{new Date(data.releaseTime).toLocaleDateString()}</span>
          <span>{new Date(data.releaseTime).toLocaleTimeString()}</span>
        </p>
        <div
          className={style["content"]}
          dangerouslySetInnerHTML={{ __html: data.content }}
        ></div>
      </div>
      <div className={style["fix-bottom"]}>
        <div className={style["item"]} onClick={addCollect}>
          <img
            src={data.whetherCollection === 1 ? collect2 : collect1}
            alt=""
          />
        </div>
        <div className={style["item"]}>
          <img src={share} alt="" />
        </div>
      </div>
    </div>
  );
};

export default Index;
